import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton, QVBoxLayout, QWidget, QMessageBox, QTabWidget, QLabel
import pyodbc
from MainWidget import MainWidget

# 注册界面类
class RegisterSystem(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("注册界面")
        self.setGeometry(100, 100, 300, 200)

        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # 创建用户名和密码输入框
        self.username = QLineEdit(self)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.confirm_password = QLineEdit(self)
        self.confirm_password.setEchoMode(QLineEdit.Password)

        # 创建注册按钮
        self.register_button = QPushButton("注册", self)
        self.register_button.clicked.connect(self.register_user)

        layout.addWidget(QLabel("用户名:"))
        layout.addWidget(self.username)
        layout.addWidget(QLabel("密码:"))
        layout.addWidget(self.password)
        layout.addWidget(QLabel("确认密码:"))
        layout.addWidget(self.confirm_password)
        layout.addWidget(self.register_button)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def register_user(self):
        # 这里添加注册逻辑
        username = self.username.text()
        password = self.password.text()
        confirm_password = self.confirm_password.text()

        if password != confirm_password:
            QMessageBox.information(self, "错误", "两次输入的密码不一致！")
            return

        try:
            # 连接数据库
            conn = self.connect_to_database()
            if conn:
                # 执行插入操作
                cursor = conn.cursor()
                # 这里假设密码以明文存储，实际应用中应该使用加密存储
                cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
                conn.commit()  # 提交事务
                QMessageBox.information(self, "成功", "注册成功！")
            else:
                QMessageBox.information(self, "错误", "无法连接到数据库！")
        except Exception as e:
            QMessageBox.information(self, "错误", "注册失败：{}".format(str(e)))

    def connect_to_database(self):
        # 数据库连接字符串
        conn_str = (
            r'DRIVER={SQL Server Native Client 11.0};'
            r'SERVER=localhost;'
            r'DATABASE=users;'
            r'Trusted_Connection=Yes;'
        )
        
        try:
            conn = pyodbc.connect(conn_str)
            return conn
        except Exception as e:
            print("数据库连接失败：", e)
            return None

# 登录界面类
class LoginSystem(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("登录界面")
        self.setGeometry(100, 100, 300, 200)
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # 创建用户名和密码输入框
        self.username = QLineEdit(self)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)

        # 创建登录按钮
        self.login_button = QPushButton("登录", self)
        self.login_button.clicked.connect(self.login_user)  # 连接到login_user方法

        layout.addWidget(QLabel("用户名:"))
        layout.addWidget(self.username)
        layout.addWidget(QLabel("密码:"))
        layout.addWidget(self.password)
        layout.addWidget(self.login_button)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def login_user(self):
        username = self.username.text().strip()  # 去除两端空格
        password = self.password.text().strip()  # 去除两端空格
        conn = self.connect_to_database()
        if conn:
            try:
                cursor = conn.cursor()
                cursor.execute("SELECT password FROM users WHERE username = ?", (username,))
                user_record = cursor.fetchone()
                if user_record:
                    db_password = user_record[0].strip()  # 从数据库中取出的密码
                    # 调试信息
                    print(f"输入的密码: '{password}'")
                    print(f"数据库中的密码: '{db_password}'")
                    if db_password == password:  # 假设密码以明文存储
                        QMessageBox.information(self, "成功", "登录成功！")
                        self.main_widget = MainWidget()  # 假设 MainWidget 是手写数字识别的主界面
                        self.main_widget.show()
                        self.close()  # 关闭登录窗口
                    else:
                        QMessageBox.information(self, "错误", "密码错误！")
                else:
                    QMessageBox.information(self, "错误", "用户名不存在！")
            except Exception as e:
                QMessageBox.information(self, "错误", "登录时发生错误，请稍后再试。")
            finally:
                cursor.close()
                conn.close()
        else:
            QMessageBox.information(self, "错误", "无法连接到数据库！")

    
    def connect_to_database(self):
        # 数据库连接字符串
        conn_str = (
            r'DRIVER={SQL Server Native Client 11.0};'
            r'SERVER=localhost;'
            r'DATABASE=users;'
            r'Trusted_Connection=Yes;'
        )
        
        try:
            conn = pyodbc.connect(conn_str)
            return conn
        except Exception as e:
            print("数据库连接失败：", e)
            return None

# 主窗口类
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("手写数字识别系统")
        self.setGeometry(300, 300, 400, 300)

        # 创建标签页
        self.tabs = QTabWidget()
        self.tab_login = LoginSystem()  # 确保LoginSystem类没有parent参数
        self.tab_register = RegisterSystem()

        self.tabs.addTab(self.tab_login, "登录")
        self.tabs.addTab(self.tab_register, "注册")

        central_widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)


# 主函数
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())